#!/bin/bash -e

function info() {
echo Usage: `basename $0` '[-t backup_destination] file [file2 ...]'
exit 1
}

while getopts  ":s:t:D" opt
do
	case  $opt  in
	s) sample_name=$OPTARG;;
	t) type=$OPTARG;;
	D) nodir=T;;
	*) info;;
	esac
done
shift $(($OPTIND - 1))

if [ -z "$1" ]; then info; fi


if [ -z "$type" ]; then
	type=cnv;
	dest_sub=.cnvsc
elif test "$type" = "cnv"; then
	dest_sub=.cnvsc
elif test "$type" = "snp"; then
	dest_sub=.snp
elif test "$type" = "tes"; then
	dest_sub=.tes
elif test "$type" = "info"; then
	dest_sub=.info
else
	if
	echo $type |grep -P '^(snp|cnv|methylation|info|tes|test|project)\/'
	then
	dest_sub=.$type
	else
	echo `basename $0` type wrong.
	exit 1
	fi
fi


. $var

if test -z "$nodir"; then
dir0=$(pwd |awk -F'/' '{print $NF}')
fi

dir=$dest/$dest_sub/$dir0
echo destination: $dir

if test ! -d $dir; then
mkdir -p $dir
# chmod 775 $dir
fi

for fil; do
    if test -e $fil; then
    fils="$fils $fil"
    fi
done

echo $fils

# cp -r --backup=numbered --preserve=timestamps -t $dir $@
cp -r --backup=numbered --preserve=timestamps -t $dir $fils

# for file in $(ls -A $dir); do
# if test -d $file; then
# chmod -R 770 $dir/$file
# else
# chmod 660 $dir/$file
# fi
# done

list=$dest/$dest_sub/.list

if test -e $list; then
	cut -f1 $list >list1
	dir1=^$dir0$
	if grep $dir1 list1; then
		rm list1
	else
		rm list1
		echo -e $dir0'\t'`date -r $( ls -1t |sed -n '1p') +%s`'\t'`pwd` >> $dest/$dest_sub/.list
	fi
	
else
	echo -e $dir0'\t'`date -r $( ls -1t |sed -n '1p') +%s`'\t'`pwd` >> $dest/$dest_sub/.list
fi

cd $dest/$dest_sub
cat $dest/$dest_sub/.list |sort -r -k2 |format_html_index.pl -n$type |cat $tools_path/html/header.html - $tools_path/html/footer.html > $dest/$dest_sub/index.html